<template>
  <div class="order-rating-view-bg">
    <el-card class="order-rating-view-card">
      <div class="order-rating-view-header">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <div class="order-rating-view-title">订单评价详情</div>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" size="32"><Loading /></el-icon>
        <div>正在加载评价信息...</div>
      </div>
      
      <div v-else-if="rating" class="rating-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单编号">{{ orderNumber || `订单ID: ${orderId}` }}</el-descriptions-item>
          <el-descriptions-item label="评价时间">{{ formatTime(rating.rating_time || rating.create_time) }}</el-descriptions-item>
          <el-descriptions-item label="评分">
            <el-rate :model-value="rating.rating" disabled show-score />
          </el-descriptions-item>
          <el-descriptions-item label="评价内容">
            <div class="rating-comment">
              {{ rating.comment || rating.content || '暂无评价内容' }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="评价图片" v-if="rating.image_url || rating.image">
            <div class="rating-image">
              <el-image 
                :src="rating.image_url || rating.image" 
                :preview-src-list="[rating.image_url || rating.image]"
                fit="cover"
                class="comment-image"
              />
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="审核状态" v-if="rating.audit_status !== undefined">
            <el-tag :type="getAuditStatusType(rating.audit_status)">
              {{ getAuditStatusText(rating.audit_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核结果" v-if="rating.audit_result">
            <div class="audit-result">{{ rating.audit_result }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="调试信息" v-if="true">
            <div style="font-size: 12px; color: #999;">
              <div>订单ID: {{ orderId }}</div>
              <div v-if="rating">
                <div v-for="(value, key) in rating" :key="key" style="margin: 2px 0;">
                  <span v-if="key === 'id'">编号: {{ value }}</span>
                  <span v-else-if="key === 'passenger_id'">乘客ID: {{ value }}</span>
                  <span v-else-if="key === 'driver_id'">司机ID: {{ value }}</span>
                  <span v-else-if="key === 'rating'">评分: {{ value }}</span>
                  <span v-else-if="key === 'comment'">评价: {{ value }}</span>
                  <span v-else-if="key === 'image_url'">图片: {{ value || '无' }}</span>
                  <span v-else-if="key === 'rating_time'">时间: {{ formatTime(value) }}</span>
                  <span v-else-if="key === 'audit_status'">审核状态: {{ getAuditStatusText(value) }}</span>
                  <span v-else-if="key === 'audit_time'">审核时间: {{ value || '无' }}</span>
                  <span v-else-if="key === 'audit_result'">审核结果: {{ value || '无' }}</span>
                  <span v-else-if="key === 'is_sensitive'">敏感内容: {{ value ? '是' : '否' }}</span>
                  <span v-else-if="key === 'order'">订单: {{ value }}</span>
                  <span v-else>{{ key }}: {{ value }}</span>
                </div>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div v-else class="no-rating">
        <el-descriptions :column="1" border style="margin-bottom: 20px;">
          <el-descriptions-item label="订单编号">{{ orderNumber || `订单ID: ${orderId}` }}</el-descriptions-item>
        </el-descriptions>
        <el-empty description="该订单暂无评价信息" />
        <div style="margin-top: 20px; text-align: center; color: #999; font-size: 12px;">
          <div>调试信息:</div>
          <div>订单ID: {{ orderId }}</div>
          <div>订单编号: {{ orderNumber }}</div>
          <div>loading状态: {{ loading }}</div>
          <div>rating数据: {{ rating ? '有数据' : '无数据' }}</div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { commentAPI } from '@/api/order'

const route = useRoute()
const router = useRouter()
const orderId = route.params.id
const orderNumber = ref('')
const rating = ref(null)
const loading = ref(true)

function goBack() {
  router.go(-1)
}

function formatTime(time) {
  if (!time) return '--'
  return new Date(time).toLocaleString('zh-CN')
}

function getAuditStatusType(status) {
  switch (status) {
    case 0: return 'warning'  // 待审核
    case 1: return 'success'  // 审核通过
    case 2: return 'danger'   // 审核拒绝
    default: return 'info'
  }
}

function getAuditStatusText(status) {
  switch (status) {
    case 0: return '待审核'
    case 1: return '审核通过'
    case 2: return '审核拒绝'
    default: return '未知状态'
  }
}

async function fetchRating() {
  try {
    loading.value = true
    console.log('开始获取评价信息，订单ID:', orderId) // 调试信息

    // 首先获取订单信息
    try {
      const orderRes = await fetch(`http://127.0.0.1:8000/order/orders/${orderId}/`)
      if (orderRes.ok) {
        const orderData = await orderRes.json()
        orderNumber.value = orderData.order_number
        console.log('获取到订单信息:', orderData) // 调试信息
      }
    } catch (error) {
      console.error('获取订单信息失败:', error)
      orderNumber.value = `订单ID: ${orderId}`
    }

    // 尝试多种方式获取评价信息
    let foundRating = null

    // 方法1: 使用新的评论API
    try {
      console.log('尝试使用新评论API获取评价...') // 调试信息
      const ratingRes = await commentAPI.getComments()
      console.log('新评论API响应:', ratingRes) // 调试信息
      
      if (ratingRes && ratingRes.data && Array.isArray(ratingRes.data)) {
        // 直接查找订单ID匹配的评价
        foundRating = ratingRes.data.find(r => r.order_id == orderId)
        console.log('在新API中找到评价:', foundRating) // 调试信息
      } else if (ratingRes && ratingRes.data && ratingRes.data.comments && Array.isArray(ratingRes.data.comments)) {
        // 如果数据在 comments 字段中
        foundRating = ratingRes.data.comments.find(r => r.order_id == orderId)
        console.log('在新API comments中找到评价:', foundRating) // 调试信息
      }
    } catch (error) {
      console.error('新评论API获取失败:', error)
    }

    // 方法2: 如果方法1失败，尝试使用旧版评价API
    if (!foundRating) {
      try {
        console.log('尝试使用旧版评价API...') // 调试信息
        const oldRatingRes = await fetch(`http://127.0.0.1:8000/order/ratings/`)
        if (oldRatingRes.ok) {
          const oldRatingData = await oldRatingRes.json()
          console.log('旧版评价API响应:', oldRatingData) // 调试信息
          
          if (oldRatingData && Array.isArray(oldRatingData)) {
            foundRating = oldRatingData.find(r => r.order == orderId || r.order_id == orderId)
            console.log('在旧版API中找到评价:', foundRating) // 调试信息
          }
        }
      } catch (oldError) {
        console.error('旧版评价API获取失败:', oldError)
      }
    }

    // 方法3: 如果都失败，尝试直接查询特定订单的评价
    if (!foundRating) {
      try {
        console.log('尝试直接查询订单评价...') // 调试信息
        const directRes = await fetch(`http://127.0.0.1:8000/order/comment/crud/?order_id=${orderId}`)
        if (directRes.ok) {
          const directData = await directRes.json()
          console.log('直接查询响应:', directData) // 调试信息
          
          if (directData && Array.isArray(directData) && directData.length > 0) {
            foundRating = directData[0] // 取第一个评价
            console.log('直接查询找到评价:', foundRating) // 调试信息
          }
        }
      } catch (directError) {
        console.error('直接查询失败:', directError)
      }
    }

    // 设置评价数据
    if (foundRating) {
      rating.value = foundRating
      console.log('最终设置的评价数据:', rating.value) // 调试信息
    } else {
      console.log('未找到任何评价数据') // 调试信息
      rating.value = null
    }

  } catch (error) {
    console.error('获取评价信息失败:', error)
    ElMessage.error('获取评价信息失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 设置默认的订单号
  orderNumber.value = `订单ID: ${orderId}`
  fetchRating()
})
</script>

<style scoped>
.order-rating-view-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #fff 60%, #e6f7ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.order-rating-view-card {
  width: 100%;
  max-width: 600px;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(34,34,34,0.08);
  padding: 32px 36px 24px 36px;
  position: relative;
}

.order-rating-view-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.order-rating-view-title {
  font-size: 26px;
  font-weight: bold;
  color: #222;
  text-align: center;
  margin: 0 auto;
  letter-spacing: 2px;
}

.loading-container {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.rating-content {
  margin-top: 20px;
}

.rating-comment {
  line-height: 1.6;
  color: #666;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  min-height: 60px;
}

.rating-image {
  margin-top: 10px;
}

.comment-image {
  width: 200px;
  height: 150px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.audit-result {
  line-height: 1.6;
  color: #666;
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 8px;
  border-left: 4px solid #1890ff;
}

.no-rating {
  text-align: center;
  padding: 40px 20px;
}
</style>
